﻿using System;
using System.Linq;
using System.Windows.Navigation;
using System.Collections.Generic;
using System.ComponentModel.Composition;

namespace GlobalOfficeTools.Framework.ViewNavigation
{
    public class NavigationController : INavigationContentLoader
    {
        #region Private Fields 
        public PageResourceContentLoader _pageResourceContentLoader = new PageResourceContentLoader();
        private Uri targetUri;
        #endregion

        #region Public Properties 
        [ImportMany("View", AllowRecomposition=true)]
        public IEnumerable<Lazy<object, IViewMetadata>> _viewLazy { get; set; }
        #endregion

        #region Constructor 
        public NavigationController() 
        {
            CompositionInitializer.SatisfyImports(this);
        }
        #endregion

        #region INavigationContentLoader Implementation 
        public IAsyncResult BeginLoad(Uri targetUri, Uri currentUri, AsyncCallback userCallback, object asyncState) 
        {
            this.targetUri = targetUri;
            return _pageResourceContentLoader.BeginLoad(targetUri, currentUri, userCallback, asyncState);
        }
        public bool CanLoad(Uri targetUri, Uri currentUri) 
        {
            return true;
        }
        public void CancelLoad(IAsyncResult asyncResult) 
        {
            //throw new NotImplementedException();
        }
        public LoadResult EndLoad(IAsyncResult asyncResult) 
        {
            var oView = _viewLazy.Single(x => x.Metadata.Name == targetUri.OriginalString).Value;
            return new LoadResult(oView);
        }
        #endregion
    }
}
